package com.stox.shared.model;

import java.text.ParseException;
import java.util.Date;

import com.stox.shared.model.exception.StoxException;
import com.stox.shared.model.intf.HasDate;
import com.stox.shared.util.Constant;
import com.stox.shared.util.StringUtil;

public class Bar implements Comparable<Bar>, HasDate {

	private double open;
	private double high;
	private double low;
	private double close;
	private double volume;
	private Date date;
	private Long scripId;
	private transient Scrip scrip;

	public Bar() {

	}

	public Bar(final Long scripId, final String text) {
		this.scripId = scripId;
		final String[] tokens = text.split(",");
		if ((0 < tokens.length) && StringUtil.hasText(tokens[0])) {
			try {
				date = Constant.dateFormat.parse(tokens[0]);
			} catch (final ParseException e) {
				throw new StoxException(e);
			}
		}
		if ((1 < tokens.length) && StringUtil.hasText(tokens[1])) {
			open = Double.parseDouble(tokens[1]);
		}
		if ((2 < tokens.length) && StringUtil.hasText(tokens[2])) {
			high = Double.parseDouble(tokens[2]);
		}
		if ((3 < tokens.length) && StringUtil.hasText(tokens[3])) {
			low = Double.parseDouble(tokens[3]);
		}
		if ((4 < tokens.length) && StringUtil.hasText(tokens[4])) {
			close = Double.parseDouble(tokens[4]);
		}
		if ((5 < tokens.length) && StringUtil.hasText(tokens[5])) {
			volume = Double.parseDouble(tokens[5]);
		}
	}

	@Override
	public String toString() {
		return Constant.dateFormat.format(getDate()) + "," + getOpen() + "," + getHigh() + "," + getLow() + "," + getClose() + "," + getVolume();
	}

	@Override
	public int compareTo(final Bar o) {
		return null == o ? 1 : date.compareTo(o.getDate());
	}

	public double getRange() {
		return high - low;
	}

	public double getMid() {
		return (high + low) / 2;
	}

	public double getOpen() {
		return open;
	}

	public void setOpen(final double open) {
		this.open = open;
	}

	public double getHigh() {
		return high;
	}

	public void setHigh(final double high) {
		this.high = high;
	}

	public double getLow() {
		return low;
	}

	public void setLow(final double low) {
		this.low = low;
	}

	public double getClose() {
		return close;
	}

	public void setClose(final double close) {
		this.close = close;
	}

	public double getVolume() {
		return volume;
	}

	public void setVolume(final double volume) {
		this.volume = volume;
	}

	@Override
	public Date getDate() {
		return date;
	}

	public void setDate(final Date date) {
		this.date = date;
	}

	public Scrip getScrip() {
		return scrip;
	}

	public void setScrip(final Scrip scrip) {
		this.scrip = scrip;
	}

	public Long getScripId() {
		return scripId;
	}

	public void setScripId(final Long scripId) {
		this.scripId = scripId;
	}

}
